document.addEventListener('DOMContentLoaded', function () {

    // 只监听标题包含 phpMyAdmin 的页面
    if (document.title.indexOf('phpMyAdmin') == -1) {
        return;
    }

    // 是否已添加全局样式
    let globalStyle = 0;

    // 已添加的样式
    let valueStyles = [];

    // 用于判断数据是否有变化
    let oldContents = [];

    // 并发控制
    let mutexLock = 0;

    // 自动转换
    let isAuto = false;

    // 特殊字段
    let specailList = [];

    // 字段规则
    let specailRule = 0;

    // 每1秒检测自动转换
    setInterval(function () {
        if (isAuto && !mutexLock) {
            document.querySelectorAll('table.table_results').forEach((table, index) => {
                let nowContent = table.innerText + table.getAttribute('data-uniqueid');
                if (oldContents[index] != nowContent) {
                    transform();
                }
            });
        }
    }, 1000);

    // Ctrl + 鼠标左键， 或 Alt + 鼠标左键
    document.addEventListener('mousedown', event => {
        if (event.ctrlKey && event.button == 0) {
            if (!mutexLock) {
                transform();
            }
        }

        if (event.altKey && event.button == 0) {
            reset();
        }
    });

    // 读取配置
    chrome.storage.local.get(['auto_transform', 'special_list', 'special_rule'], function (res) {
        if (res.auto_transform) {
            isAuto = true;
        }
        if (res.special_list) {
            specailList = getSpecailList(res.special_list);
        }
        if (res.special_rule) {
            specailRule = 1;
        }
    });

    // 监听配置变更
    chrome.storage.onChanged.addListener(function (changes) {
        for (let key in changes) {
            switch (key) {
                case 'auto_transform':
                    isAuto = changes[key].newValue;
                    break
                case 'special_list':
                    specailList = getSpecailList(changes[key].newValue);
                    break;
                case 'special_rule':
                    specailRule = changes[key].newValue;
                    break;
            }
        }
    });

    /**
     * 特殊字段列表
     * @param {String} text
     * @return {Array}
     */
    function getSpecailList (text) {
        return text.split(/\r?\n/).map(function (value) {
            if (value.indexOf('*') == -1) {
                return value;
            } else {
                let pattern = '^' + value.replace(/\*/g, '.*') + '$';
                return new RegExp(pattern);
            }
        });
    }

    /**
     * 判断某个字段是否在设置的特殊字段列表中
     * @param {String} field
     * @return {Boolean}
     */
    function matchField (field) {
        for (let item of specailList) {
            if (typeof item == 'string') {
                if (item == field) {
                    return true;
                }
            } else {
                if (item.test(field)) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 开始转换
     */
    function transform () {
        mutexLock = 1;

        let style = '';

        document.querySelectorAll('table.table_results').forEach((table, index) => {
            oldContents[index] = table.innerText + table.getAttribute('data-uniqueid');

            let fieldList = [];

            table.querySelectorAll('th[data-column]').forEach((th, i) => {
                fieldList[i] = th.getAttribute('data-column');
            });

            table.querySelectorAll('td.data').forEach((td, i) => {
                let k = i % fieldList.length;
                let field = fieldList[k];
                let isMatch = matchField(field);

                // 不转换设置的字段
                if (specailRule == 0 && isMatch) {
                    return;
                }

                // 只转换设置的字段
                if (specailRule == 1 && !isMatch) {
                    return;
                }

                // 字段类型限制
                if (td.getAttribute('data-type') != 'int') {
                    return;
                }

                let value = td.innerText;

                if (/time2date/.test(td.className)) {
                    let pattern = new RegExp('time2date-' + value);
                    // 存在样式名表示数据未变动
                    if (pattern.test(td.className)) {
                        return;
                    }
                    // 移除旧样式名
                    td.className = td.className.replace(/time2date(-\d+)?/g, '').trim();
                }

                // 只对以1开头的10位数的单元格进行转换
                if (!/^1\d{9}$/.test(value)) {
                    return;
                }

                let date = new Date(value * 1000);
                let content = formatDate(date);
                let className = 'time2date-' + value;

                if (valueStyles.indexOf(className) == -1) {
                    valueStyles.push(className);
                    style += `td.${className}:after{content:"${content}"}`;
                }

                td.className += ' time2date ' + className;

                // 设置 phpMyAdmin 4.9 固定表头的最小宽度
                if (valueStyles.indexOf(field) == -1) {
                    valueStyles.push(field);
                    style += `th.column_heading[data-column="${field}"]{min-width:213px}`;
                }
            });
        });

        if (style) {
            style = '<style class="time2date-value">' + style + '</style>';
            document.head.insertAdjacentHTML('beforeend', style);
            addGlobalStyle();
        }

        mutexLock = 0;
    }

    /**
     * 重置
     */
    function reset () {
        document.querySelectorAll('table.table_results').forEach(table => {
            table.querySelectorAll('td[class~=time2date]').forEach(td => {
                td.className = td.className.replace(/time2date(-\d+)?/g, '').trim();
            });
        });

        document.querySelectorAll('.time2date-global, .time2date-value').forEach(element => {
            element.remove();
        });

        globalStyle = 0;
        valueStyles = [];
    }

    /**
     * 添加全局样式
     */
    function addGlobalStyle () {
        if (globalStyle) {
            return;
        }

        let style = `
        <style class="time2date-global">
            /* 设置 phpMyAdmin 5.0 固定表头的层次 */
            th.sticky {
                z-index: 1;
            }
            td.time2date {
                position: relative;
                min-width: 232px;
                box-sizing: border-box;
                text-align: right !important;
            }
            td.time2date::after {
                position: absolute;
                top: 50%;
                left: 2px;
                margin-top: -11px;
                background: #03a9f42e;
                display: block;
                width: 138px;
                height: 22px;
                line-height: 22px;
                text-align: center;
                border-radius: 2px;
                right: 100%;
                font-style: normal;
            }
        </style>`;

        document.head.insertAdjacentHTML('beforeend', style);
        globalStyle = 1;
    }

    /**
     * 将时间差转换成日期格式
     * @param {Date} now
     * @return {String}
     */
    function formatDate (now) {
        let year = now.getFullYear();
        let month = now.getMonth() + 1;
        let date = now.getDate();
        let hour = now.getHours();
        let minute = now.getMinutes();
        let second = now.getSeconds();

        month = month < 10 ? '0' + month : month;
        date = date < 10 ? '0' + date : date;
        hour = hour < 10 ? '0' + hour : hour;
        minute = minute < 10 ? '0' + minute : minute;
        second = second < 10 ? '0' + second : second;

        return year + '-' + month + '-' + date + ' ' + hour + ':' + minute + ':' + second;
    }
});